var width = 480;
var height = 760;

var tabWidth = width / 3;
var tabHeight = height / 10;

var menuHeight = 40;
var menuWidth = 200;

var listElementHeight = height / 5;

var tabFontSize = width / 20;
var WEBSERVICE = "http://student.labranet.jamk.fi/~H8145/webservice/index.php";
var DATASERVICE = "http://student.labranet.jamk.fi/~H8145/data";

var currentUser = null;
var chosenReceipt = null;

var txtIngredients = new Array();
var txtSteps = new Array();
var txtComments = new Array();

var receipts = new Array();
var favReceipts = new Array();
var ingredients = new Array();
var ingCount = 1;

var favReceipt = false;
var update = true;

var ingCBs = new Array();
var ingContainers = new Array();
var txtTypeOfAmounts = new Array();

var addedSteps = 1;
var addedIngredients = 0;

var effort = "";
var selectedIngredients = new Array(6);
var txtAmounts = new Array();
var stepsCreated = new Array();

var selectedIngredients = new Array(3);
var filterIngredientsContainer;
var filterIngCBs;

var filter = false;
var rfName;
var ufName;

function login(loginName, password){
    var result = false;
    if(loginName === "" || password === ""){
        txtError.text = "Loginname or Password empty.";
    } else {
        var getData = "loginName="+loginName+"&password="+password;
        var url = WEBSERVICE + "/user/login?" + getData;
        sendRequest(url, function(json){
            if(json.user.error){
                txtError.text = json.user.error;
            } else {
                currentUser = json.user;
                loginContent.visible = false;
                tabWidget.visible = true;
            }
        });
        result = true;
    }
    return result;
}

function logout(){
    currentUser = null;
    tabWidget.visible = false;
    loginContent.visible = true;
}

function showStream(sorting) {
    var join = "JOIN user ON user.id = receipt.user_id ";
    var sort = "ORDER BY " + dcFirst(sorting) + " DESC";
    var whereString = "deleted=false";
    var getData = "join=" + join + "&sort=" + sort + "&where[]=" + whereString;
    var url = WEBSERVICE + "/receipt/filter?" + getData;
    filter = false;
    getReceipts(url);
}
function getReceipts(url){
    sendRequest(url, function(json){
        stream_model.clear();
        receipts = json.receipts;
        for(var i = 0; i < receipts.length; i++){
            var receipt = receipts[i];
            var star = new Array();
            for(var s = 0; s < 5;s++){
                star.push("resources/0_0.png");
            }
            var rating = Math.floor(receipt.rating);
            for(var j = 0; j < rating; j++){
                star[j] = "resources/1_0.png";
            }
            if(receipt.rating - rating >= 0.5){
                star[rating] = "resources/0_5.png";
            }
            var recImage = DATASERVICE + "/" + receipt.id + ".png";

            stream_model.append({"id" : receipt.id, "date" : sanDate(receipt.date), "name" : receipt.name
                      ,"description" : receipt.description, "effort" : receipt.effort
                      ,"countClicks" : receipt.countClicks, "rating" : receipt.rating
                      ,"duration" : sanDuration(receipt.duration), "loginName" : receipt.loginName
                      ,"star1": star[0], "star2": star[1], "star3": star[2], "star4": star[3]
                      ,"star5": star[4], "recImage": recImage});
        }
    });
}

// for showing the receipt, have to get all the data
function initReceipt(id){
    var join = "JOIN user ON user.id = receipt.user_id ";
    var getData = "join=" + join + "&where[]=deleted=false&where[]= receipt.id="+id;
    var url = WEBSERVICE + "/receipt/filter?" + getData;
    // first get the receipt based on the id
    favReceipt = isFavReceipt(id);
    btnAddFavourite.text = favReceipt ? "remove from favourite" : "add to favourite";
    sendRequest(url, function(json){
        chosenReceipt = json.receipts[0];
        var getData = "receipt_id=" + chosenReceipt.id;
        var url = WEBSERVICE + "/receipt/getIngredients?" + getData;
        // after setting the chosen receipt, get the ingredients
        sendRequest(url, function(json){
            chosenReceipt.ingredients = json.ingredients;
            var getData = "receipt_id=" + chosenReceipt.id;
            var url = WEBSERVICE + "/receipt/getSteps?" + getData;
            // after setting the ingredients, get the steps
            sendRequest(url, function(json){
                chosenReceipt.steps = json.step;
                var getData = "receipt_id=" + chosenReceipt.id;
                var url = WEBSERVICE + "/comment/commentsByReceipt?" + getData;
                // after setting the steps, get the comments
                sendRequest(url, function(json){
                    chosenReceipt.comments = json.comments;
                    // putting values into fields
                    imgReceipt.source = DATASERVICE + "/" + chosenReceipt.id + ".png";
                    receiptDuration.text = sanDuration(chosenReceipt.duration);
                    receiptEffort.text = chosenReceipt.effort;
                    receiptDate.text = sanDate(chosenReceipt.date);
                    receiptClicks.text = parseInt(chosenReceipt.countClicks) + 1;
                    receiptUsername.text = chosenReceipt.loginName;
                    receiptName.text = chosenReceipt.name;
                    receiptDescription.text = chosenReceipt.description;

                    resetTexts();

                    var countIng = chosenReceipt.ingredients.length;
                    for(var i = 0; i < countIng; i++){
                        var ing = chosenReceipt.ingredients[i];
                        var textName = 'Text { height: 25; y: '+(i*30)+'; width: 100; text: "'+ing.name+'"; }';
                        var textAmount = 'Text { height: 25; x: 110; y: '+(i*30)+'; width: 100; text: "'+ing.amount+'"; }';
                        var textType = 'Text { height: 25; x: 220; y: '+(i*30)+'; width: 100; text: "'+ing.typeOfAmount+'"; }';
                        txtIngredients.push(Qt.createQmlObject('import QtQuick 2.3; ' + textName, detailIngredients));
                        txtIngredients.push(Qt.createQmlObject('import QtQuick 2.3; ' + textAmount, detailIngredients));
                        txtIngredients.push(Qt.createQmlObject('import QtQuick 2.3; ' + textType, detailIngredients));
                    }
                    sep1.y = countIng * 40 + 280;
                    lblStep.y = sep1.y + 10;
                    steps.y = lblStep.y + 30;

                    var countStep = chosenReceipt.steps.length;
                    for(var j = 0; j < countStep; j++){
                        var step = chosenReceipt.steps[j];
                        var textNumber = 'Text { y: '+(j*30)+'; width: 100; text: "Step '+step.number+': "; }';
                        var textDescription = 'Text { x: 110; y: '+(j*30)+'; width: 100; text: "'+step.description+'"; }';
                        txtSteps.push(Qt.createQmlObject('import QtQuick 2.3; ' + textNumber, steps));
                        txtSteps.push(Qt.createQmlObject('import QtQuick 2.3; ' + textDescription, steps));
                    }

                    sep2.y = steps.y + countStep * 40;
                    lblComment.y = sep2.y + 10;
                    comments.y = lblComment.y + 30;

                    var countComment = 1;
                    if(chosenReceipt.comments.error){
                        var textError = 'Text { y: '+(30+15)+'; width: '+width+'; text: "'+chosenReceipt.comments.error+'"; }';
                        txtComments.push(Qt.createQmlObject('import QtQuick 2.3; ' + textError, comments));
                    } else {
                        countComment = chosenReceipt.comments.length;
                        for(var c = 0; c < countComment; c++){
                            var comment = chosenReceipt.comments[c];
                            var textUser = 'Text { y: '+(c*30)+'; width: '+width+'; text: "'+comment.loginName+'(' + comment.date + ')"; }';
                            var textComment = 'Text { y: '+(c*30+15)+'; width: '+width+'; text: "'+comment.text+'"; }';
                            txtComments.push(Qt.createQmlObject('import QtQuick 2.3; ' + textUser, comments));
                            txtComments.push(Qt.createQmlObject('import QtQuick 2.3; ' + textComment, comments));
                        }
                    }

                    txtComment.y = comments.y + countComment * 30 + 10;
                    addComment.y = txtComment.y + 30;
                    addFavourite.y = addComment.y + 40;

                    var star = new Array();
                    for(var s = 0; s < 5;s++){
                        star.push("resources/0_0.png");
                    }
                    var rating = Math.floor(chosenReceipt.rating);
                    for(var q = 0; q < rating; q++){
                        star[q] = "resources/1_0.png";
                    }
                    if(chosenReceipt.rating - rating >= 0.5){
                        star[rating] = "resources/0_5.png";
                    }

                    star1.source = star[0];
                    star2.source = star[1];
                    star3.source = star[2];
                    star4.source = star[3];
                    star5.source = star[4];

                    // updating count clicks
                    if(update){
                        var count = parseInt(chosenReceipt.countClicks) + 1;
                        var getData = "name="+chosenReceipt.name+"&description="+chosenReceipt.description;
                        getData += "&effort="+chosenReceipt.effort+"&duration="+chosenReceipt.duration;
                        getData += "&countClicks="+count+"&receipt_id="+chosenReceipt.id;
                        var url = WEBSERVICE + "/receipt/update?" + getData;
                        sendRequest(url, function(json){

                        });
                    }
                    update = true;
                });
            });
        });
    });
}

function btnFavourite(){
    var url = WEBSERVICE + "/receipt/";
    url += favReceipt ? "removeFromFavourite" : "addToFavourite";
    favReceipt = !favReceipt;
    var getData = "?user_id="+currentUser.id+"&receipt_id="+chosenReceipt.id;
    sendRequest(url + getData, function(json){
        btnAddFavourite.text = favReceipt ? "remove from favourite" : "add to favourite";
    });
}

function addToFriendList(){
    var getData = "user_id="+currentUser.id+"&friend_id="+chosenReceipt.user_id;
    var url = WEBSERVICE + "/user/addToFriendList?" + getData;
    sendRequest(url, response);
}

function showFavourites() {
    var getData = "user_id="+currentUser.id;
    var url = WEBSERVICE + "/receipt/favouriteReceipts?" + getData;
    sendRequest(url, function(json){
        favourites_model.clear();
        favReceipts = json.receipts;
        for(var i = 0; i < favReceipts.length; i++){
            var receipt = favReceipts[i];
            var star = new Array();
            for(var s = 0; s < 5; s++){
                star.push("resources/0_0.png");
            }
            var rating = Math.floor(receipt.rating);
            for(var j = 0; j < rating; j++){
                star[j] = "resources/1_0.png";
            }
            if(receipt.rating - rating >= 0.5){
                star[rating] = "resources/0_5.png";
            }
            var recImage = DATASERVICE + "/" + receipt.id + ".png";

            favourites_model.append({"id" : receipt.id, "date" : sanDate(receipt.date), "name" : receipt.name
                      ,"description" : receipt.description, "effort" : receipt.effort
                      ,"countClicks" : receipt.countClicks, "rating" : receipt.rating
                      ,"duration" : sanDuration(receipt.duration), "loginName" : receipt.loginName
                      ,"star1": star[0], "star2": star[1], "star3": star[2], "star4": star[3]
                      ,"star5": star[4], "recImage": recImage});
        }
    });
}

function showFilter(fic1, fic2, fic3, cbFIng1, cbFIng2, cbFIng3, recfilterName, userfilterName) {
    rfName = recfilterName;
    ufName = userfilterName;

    filterIngredientsContainer = new Array();
    filterIngredientsContainer.push(fic1);
    filterIngredientsContainer.push(fic2);
    filterIngredientsContainer.push(fic3);

    filterIngCBs = new Array();
    filterIngCBs.push(cbFIng1);
    filterIngCBs.push(cbFIng2);
    filterIngCBs.push(cbFIng3);

    selectedIngredients = new Array(3);

    var url = WEBSERVICE + "/receipt/getAllIngredients";
    sendRequest(url, function(json){
        ingredients = json.ingredients;
        for(var j = 0; j < filterIngCBs.length; j++){
            filterIngCBs[j].clear();
            filterIngCBs[j].append({"name": "--"});
            for(var c = 0; c < ingredients.length; c++){
                var ing = ingredients[c];
                filterIngCBs[j].append({"name": ing.name});
            }
        }
    });
}
function addFilterIngredient(index, number, frc){
    if(index > 0){
        selectedIngredients[number] = ingredients[index-1];
        if(number < filterIngredientsContainer.length - 1){
            filterIngredientsContainer[number+1].visible = true;
            frc.y = 100 + number * 40;
        }
    }
}
function doFilter(sorting){
    filter = true;
    var join = "JOIN user ON user.id = receipt.user_id ";
    var sort = "ORDER BY " + dcFirst(sorting) + " DESC";
    var wheres = new Array();

    wheres.push(" deleted=false ");
    if(rfName.text !== ""){
        wheres.push(" receipt.name LIKE '%"+rfName.text+"%' ");
    }
    if(ufName.text !== ""){
        wheres.push(" user.loginName LIKE '%"+ufName.text+"%' ");
    }
    var ids = new Array();
    for(var i = 0; i < selectedIngredients.length; i++){
        if(typeof selectedIngredients[i] !== "undefined"){
            ids.push(selectedIngredients[i].id);
        }
    }
    if(ids.length > 0){
        var ins = "IN (" + ids.join(",") + ")";
        join += "JOIN receipt_ingredient ON receipt_ingredient.ingredient_id " + ins;
        wheres.push(" receipt_ingredient.receipt_id = receipt.id ");
    }
    var getData = "join="+join+"&sort="+sort+"&where[]="+wheres.join("&where[]=");
    var url = WEBSERVICE + "/receipt/filter?"+getData;
    console.log(url);
    getReceipts(url);
    selectedIngredients = new Array(3);
}

function initFriendList(){
    mdlFriendList.clear();
    var url = WEBSERVICE + "/user/friendList?user_id="+currentUser.id;
    sendRequest(url, function(json){
        var friends = json.friendList;
        for(var i = 0; i < friends.length; i++){
            var friend = friends[i];
            mdlFriendList.append({"loginName": friend.loginName});
        }
    });
}

function btnAddComment(comment){
    var getData = "user_id="+currentUser.id+"&receipt_id="+chosenReceipt.id+"&text="+comment+"&parent_comment_id=0";
    var url = WEBSERVICE + "/comment/create?" + getData;
    sendRequest(url, function(json){
        update = false;
        txtComment.text = "";
        initReceipt(chosenReceipt.id);
    })
}

function rate(rating){
    var amount = parseFloat(rating);
    var getData = "receipt_id="+chosenReceipt.id+"&user_id="+currentUser.id+"&amount="+amount;
    var url = WEBSERVICE + "/receipt/rate?" + getData;
    sendRequest(url, function(json){
        var star = new Array();
        chosenReceipt.rating = json.rate;
        console.log(json.rate);
        rating = Math.floor(chosenReceipt.rating);
        for(var s = 0; s < 5; s++){
            star.push("resources/0_0.png");
        }
        for(var q = 0; q < rating; q++){
            star[q] = "resources/1_0.png";
        }
        if(chosenReceipt.rating - rating >= 0.5){
            star[rating] = "resources/0_5.png";
        }
        star1.source = star[0];
        star2.source = star[1];
        star3.source = star[2];
        star4.source = star[3];
        star5.source = star[4];
    });
}

function initIngredients(){
    stepsCreated = new Array();
    selectedIngredients = new Array(6);

    ingCBs = new Array();
    ingCBs.push(addIngredient1);
    ingCBs.push(addIngredient2);
    ingCBs.push(addIngredient3);
    ingCBs.push(addIngredient4);
    ingCBs.push(addIngredient5);
    ingCBs.push(addIngredient6);

    ingContainers = new Array();
    ingContainers.push(ingContainer1);
    ingContainers.push(ingContainer2);
    ingContainers.push(ingContainer3);
    ingContainers.push(ingContainer4);
    ingContainers.push(ingContainer5);
    ingContainers.push(ingContainer6);

    txtTypeOfAmounts = new Array();
    txtTypeOfAmounts.push(txtTypeOfAmount1);
    txtTypeOfAmounts.push(txtTypeOfAmount2);
    txtTypeOfAmounts.push(txtTypeOfAmount3);
    txtTypeOfAmounts.push(txtTypeOfAmount4);
    txtTypeOfAmounts.push(txtTypeOfAmount5);
    txtTypeOfAmounts.push(txtTypeOfAmount6);

    txtAmounts = new Array();
    txtAmounts.push(ingAmount1);
    txtAmounts.push(ingAmount2);
    txtAmounts.push(ingAmount3);
    txtAmounts.push(ingAmount4);
    txtAmounts.push(ingAmount5);
    txtAmounts.push(ingAmount6);

    var url = WEBSERVICE + "/receipt/getAllIngredients";
    sendRequest(url, function(json){
        ingredients = json.ingredients;
        initIngList();

        for(var j = 0; j < ingCBs.length; j++){
            for(var i = 0; i < ingredients.length; i++){
                var ing = ingredients[i];
                ingCBs[j].append({"name": ing.name});
            }
        }
    });
}
function addIngredient(index, number){
    txtTypeOfAmounts[number-1].text = ingredients[index-1].typeOfAmount;
    if(index > 0 && number < ingCBs.length){
        ingContainers[number].visible = true;
        addedIngredients++;
        addSepIngredient.y = 300 + number * 40;
        addReceiptSteps.y = addSepIngredient.y + 20;
        addSepSteps.y = 440 + addedSteps * 30 + number * 40;
        btnAddReceipt.y = addSepSteps.y + 20;
    }
    selectedIngredients[number-1] = ingredients[index-1];
}
function initIngList(){
    for(var i = 0; i < ingCBs.length; i++){
        ingCBs[i].clear();
        ingCBs[i].append({"name": "--"});
    }
}

function addStep(){
    addedSteps++;
    var stepAdded1 = 'import QtQuick 2.3; Text{ y: '+((addedSteps-1)*35)+'; x:5; id: addStep'+addedSteps+'; width: 50; height: 30; text: "Step '+addedSteps+'"; }';
    var stepAdded2 = 'import QtQuick.Controls 1.2; TextField { y: '+((addedSteps-1)*35)+'; id: txtStep'+addedSteps+'; width: 350; height: 30; x: 60; }';
    Qt.createQmlObject(stepAdded1, addReceiptStepsContainer);
    stepsCreated.push(Qt.createQmlObject(stepAdded2, addReceiptStepsContainer));
    addSepSteps.y = 420 + addedSteps * 30 + addedIngredients * 40;
    btnAddReceipt.y = addSepSteps.y + 20;
}

function addReceipt(){
    var duration = addReceiptDuration.text;
    var name = addReceiptName.text;
    var description = addReceiptDescription.text;

    var tmpIngredients = new Array();
    for(var i = 0; i < selectedIngredients.length; i++){
        var ing = selectedIngredients[i];
        if(typeof ing != 'undefined'){
            tmpIngredients.push("ingredients[]="+selectedIngredients[i].id);
            tmpIngredients.push("amount[]="+txtAmounts[i].text);
        }
    }

    var ingredientData = tmpIngredients.join("&");
    var getData = "user_id="+currentUser.id+"&name="+name+"&description="+description+"&effort="+effort+"&duration="+duration+"&";
    getData += ingredientData;
    var url = WEBSERVICE + "/receipt/create?"+getData;
    sendRequest(url, function(json){
        var tmpSteps = new Array();
        tmpSteps.push("descriptions[]="+txtStep1.text);
        tmpSteps.push("numbers[]="+1);
        for(var j = 0; j < stepsCreated.length; j++){
            tmpSteps.push("descriptions[]="+stepsCreated[j].text);
            tmpSteps.push("numbers[]="+(j+2));
        }
        var steps = tmpSteps.join("&");
        var url = WEBSERVICE + "/receipt/createSteps?" + steps + "&receipt_id="+json;
        sendRequest(url, function(json){

        });
    });
}

function response(json){

}

function sendRequest(url, func) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.responseText != "") {
                var json = JSON.parse(request.responseText);
                func(json);
            } else {
                console.log("Check data connectivity");
            }
        }
    }
    request.open("GET", url, true);
    request.send();
}

function dcFirst(string){
    return string.charAt(0).toLowerCase() + string.slice(1);
}

function sanDate(stringDate){
    return stringDate;
}

function sanDuration(duration){
    var durInt = parseInt(duration);
    var hours = Math.floor(durInt / 60);
    var minutes = durInt % 60;
    return hours + "h " + minutes + "m";
}

function isFavReceipt(id){
    for(var i = 0; i < favReceipts.length; i++){
        if(favReceipts[i].id === id){
            return true;
        }
    }
    return false;
}

function resetTexts(){
    for(var i = 0; i < txtIngredients.length; i++){
        txtIngredients[i].destroy();
    }
    for(var j = 0; j < txtSteps.length; j++){
        txtSteps[j].destroy();
    }
    for(var c = 0; c < txtComments.length; c++){
        txtComments[c].destroy();
    }
    txtIngredients = new Array();
    txtSteps = new Array();
    txtComments = new Array();
}
